import 'dart:io';
import 'package:dio/dio.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter_changdian_football/api/app_exceptions.dart';
import 'package:flutter_changdian_football/utils/custom_logger.dart';
import 'package:flutter_changdian_football/widget/toast/custom_toast.dart';
import 'package:get/get.dart';

class MyDioSocketException implements SocketException {
  @override
  String message;

  @override
  final InternetAddress? address;

  @override
  final OSError? osError;

  @override
  final int? port;

  MyDioSocketException(
    this.message, {
    this.osError,
    this.address,
    this.port,
  });
}

// 错误处理拦截器
class ErrorInterceptor extends Interceptor {
  // 是否有网
  Future<bool> isConnected() async {
    var connectivityResult = await (Connectivity().checkConnectivity());
    return connectivityResult != ConnectivityResult.none;
  }

  @override
  Future<void> onError(DioError err, ErrorInterceptorHandler handler) async {
    // 自定义一个socket实例，因为dio原生的实例，message属于是只读的
    if (err.error is SocketException) {
      err.error = MyDioSocketException(
        '${err.error}',
        osError: err.error?.osError,
        address: err.error?.address,
        port: err.error?.port,
      );
    }
    // 是否已经连接了网络，不判断是否没网
    if (err.type == DioErrorType.other) {
      bool isConnectNetWork = await isConnected();
      if (!isConnectNetWork && err.error is MyDioSocketException) {
        err.error = "目前暂无网络可用";
        
        CustomToast.showTextToast("目前无网络可用");
      } else {
        err.error = "当前网络不可用，请检查您的网络";

        CustomToast.showTextToast("当前网络不可用，请检查您的网络");
      }
    }

    // if (err.response?.statusCode == 503) {
    //   CustomToast.showTextToast('服务繁忙，请稍后再试');
    //   return ;
    // }
    // error统一处理
    // AppException appException = AppException.create(err);
    AppException? appException;
    try {
      appException = AppException.create(err);
    } catch (e) {
      logger.d('message');
    }
    // 错误提示
    logger.d('DioError===: ${appException.toString()}====${appException?.code}');

    err.error = appException;

    // 维护页
    // if (appException?.code == 503 || appException?.code == 404) {
    //   if (Get.currentRoute != AppRoutes.redeemPage) {
    //     Get.offAllNamed(AppRoutes.redeemPage);
    //   }
    // }


    return super.onError(err, handler);
  }
}